/*Copyright (c) 2008 Martin Hinks

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Net;
using System.IO;

namespace Impersonation
{
    public enum RequestType
    {
        GET,
        POST
    }

    public enum CookieSetType
    {
        QueryString,
        Persist,
        Absolute,
        Evaluation
    }

    internal class ImpersonatedRequest
    {
        RequestType _requestType = RequestType.GET;
        string _url = String.Empty;
        string _Cookies = string.Empty;
        string postdata = string.Empty;
        Dictionary<string, string> _Variables = null;
        Impersonator _Imp = null;
        CookieSetType _cookieType = CookieSetType.QueryString;
        List<RegexMatcher> _variableSetters = new List<RegexMatcher>();

        public string PostData
        {
            get { return postdata; }
            set { postdata = value; }
        }

        public List<RegexMatcher> VariableSetters
        {
            get { return _variableSetters; }
            set { _variableSetters = value; }
        }

        public CookieSetType CookieType
        {
            get { return _cookieType; }
            set { _cookieType = value; }
        }

        public string Cookie
        {
            get { return _Cookies; }
            set { _Cookies = value; }
        }

        public string Url
        {
            get { return _url; }
            set { _url = value; }
        }

        public RequestType RequestType
        {
            get { return _requestType; }
            set { _requestType = value; }
        }

        public ImpersonatedRequest(RequestType rt, string url, Dictionary<string, string> variables, Impersonator imp)
        {
            _requestType = rt;
            _url = url;
            _Variables = variables;
            _Imp = imp;
        }

        public void DoRequest()
        {
            HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(_url);

            hwr.Referer = "";

            //Loop through cookies processing each one
            string cooks = string.Empty;

            //Add cookie
            if (_Imp.Cookie != null && _Imp.Cookie != string.Empty)
            {

                string[] cookies = _Imp.Cookie.Split(';');

                int y = 0;

                //Encode cookie
                foreach (string s2 in cookies)
                {
                    string news = s2.Trim();

                    if (y != 0)
                    {
                        cooks += "; ";
                    }
                    else
                    {
                        y++;
                    }

                    cooks += news.Replace(" ", "%20");
                }

                hwr.Headers.Add("Cookie", cooks);
            }

            hwr.UserAgent = HttpContext.Current.Request.UserAgent;

            if (_requestType == RequestType.POST)
            {
                byte[] post = System.Text.Encoding.ASCII.GetBytes(postdata);

                hwr.Method = "POST";
                hwr.ContentType = "application/x-www-form-urlencoded";
                hwr.ContentLength = postdata.Length;

                Stream newStream = hwr.GetRequestStream();
                // Send the data.
                newStream.Write(post, 0, post.Length);
                newStream.Close();
            }

            WebResponse wr = hwr.GetResponse();

            Stream s = wr.GetResponseStream();

            StreamReader sr = new StreamReader(s);

            string resp = sr.ReadToEnd();

            _Imp.Cookie = wr.Headers[HttpResponseHeader.SetCookie];

            sr.Close();

            foreach (RegexMatcher rm in VariableSetters)
            {   
                string match = rm.ReturnMatch(resp);

                if (match == string.Empty)
                {
                    Output.SendMessage("WARNING: Received no match for " + rm.Variable);
                }

                if (_Variables.ContainsKey(rm.Variable))
                {
                    _Variables.Remove(rm.Variable);
                }

                _Variables.Add(rm.Variable, match);
            }
        }
    }
}
